import sys
import time

import argparse

from libs.HueBridge import HueBridge

TT_SEC = 10

class HueScript(object):
    def __init__(self, time_dilation=1, debug=False, bridge=None):
        self.bridge = bridge

        if not isinstance(self.bridge, HueBridge):
            raise Exception("HueScript object must be instantiated with a HueBridge.")

        if time_dilation <= 0:
            time_dilation = 1

        self.time_dilation = time_dilation
        self.debug = debug
        self.logfile = ''

        self._setUpArgParser()
        self._parseArgs()

        self.makeCues()

    def _setUpArgParser(self):
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument('--debug', '-d', action='store_true',
                help='Enable debug output.')
        self.parser.add_argument('--logLocation', '-o',
                help='Location to log cues.', metavar='FILE')
        self.parser.add_argument('--timeDilation', '-td', default=1, type=float,
                help='Scale factor for transitions and script speed.', metavar='SECS')

    def _parseArgs(self):
        self.args = self.parser.parse_args()

        self.debug |= self.args.debug
        self.time_dilation = self.args.timeDilation

    def makeCues(self):
        self.cues = []

    # This needs to be implemented by a descendant.
    def getCues(self):
        return self.cues

    def addCue(self, cue):
        self.cues.append(cue)

    def __call__(self):
        now = 0

        for cue in self.getCues():
            cue.adjustForTimeDilation(self.time_dilation)
            wait = cue.idx - now

            if self.debug:
                sys.stderr.write("sleeping %s seconds...\n" % str(wait))

            time.sleep( wait )

            if self.debug:
                sys.stderr.write(str(cue))

            self.writeLog(str(cue))
            cue()

            now += wait

    def getCueListStr(self):
        s = ''

        for cue in self.cues:
            s += str(cue)

        return s

    def writeLog(self, s):
        if self.args.logLocation:
            with open(self.args.logLocation, 'wb') as f:
                f.write(s)
            return True
        return False
